<!DOCTYPE html>
<html>

<head>
    <title>联系我们</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

    <script type="application/x-javascript">
        addEventListener("load", function() {
            setTimeout(hideURLbar, 0);
        }, false);

        function hideURLbar() {
            window.scrollTo(0, 1);
        }
    </script>
    <link href="css/bootstrap.css" rel="stylesheet" type="text/css" media="all" />
    <link href="css/style.css" rel="stylesheet" type="text/css" media="all" />
    <!-- js -->
    <script src="js/jquery-1.11.1.min.js"></script>
    <script src="js/vue.js"></script>
    <!-- start-smoth-scrolling -->
    <script type="text/javascript">
        jQuery(document).ready(function($) {
            $(".scroll").click(function(event) {
                event.preventDefault();
                $('html,body').animate({
                    scrollTop: $(this.hash).offset().top
                }, 1000);
            });
        });
    </script>
    <!-- start-smoth-scrolling -->
    <link href='http://fonts.googleapis.com/css?family=Raleway:400,100,200,300,500,600,700,800,900' rel='stylesheet' type='text/css'>
</head>

<body>
   <div id="app">
         <!-- header -->
    <div class="header">
        <div class="container">
            <div class="header-nav">
                <nav class="navbar navbar-default">
                    <div class="navbar-header">
                        <a class="navbar-brand" href="index.html"><img src="images/logo.png"></a>
                    </div>
                    <div class="collapse navbar-collapse nav-wil" id="bs-example-navbar-collapse-1">
                        <ul class="nav navbar-nav">
                            <li class="hvr-bounce-to-bottom "><a href="index.html">主页</a></li>
                            <li class="hvr-bounce-to-bottom"><a href="about.html">关于</a></li>
                            <li class="hvr-bounce-to-bottom"><a href="menu.html">菜谱</a></li>
                            <li class="hvr-bounce-to-bottom"><a href="blog.html">论坛交流</a></li>
                            <li class="hvr-bounce-to-bottom active"><a href="contact.html">发布</a></li>
                            <li class="hvr-bounce-to-bottom "><a href="login.html" v-if="username==null">登录</a></li>
                            <li class="hvr-bounce-to-bottom"><a @click="logout"  >{{username}}</a></li>
                        </ul>
                    </div>

                </nav>
            </div>
        </div>
    </div>
    <!-- //header -->
    <!-- contact -->
    <div class="contact container">
        <div class="contact-main">
            <h3>{{opt}} <h4><a @click="switchType()">切换</a></h4></h3>
            <div v-if="type==1">
                <!-- 地图区域保持不变 -->
                <div class="row">
                    <div class="col-md-6">
                        <div class="contact-form">
                            <div class="form-group">
                                <label for="title">标题</label>
                                <input type="text" class="form-control" id="title" v-model="blog.title" name="title"  placeholder="请输入标题" required >
                            </div>
                            <div class="form-group">
                                <label for="tags">标签</label>
                                <select class="form-control" id="tags" name="tags" required v-model="blog.selected">
                                    <option value="">请选择分类</option>
                                    <option  v-for="item in theme">{{item.theme}}</option>
                                   
                                    <!-- 添加更多分类选项 -->
                                </select>
                                
                            </div>
                            <div class="form-group">
                                <label for="content">内容</label>
                                <textarea class="form-control" id="content" v-model="blog.desc" name="content" rows="5" placeholder="在此处编写内容……" required></textarea>
                            </div>
                            
                            <!-- 图片上传及预览部分 -->
                            <div class="form-group">
                                <label for="imageUpload">图片上传</label>
                                <input type="file" class="form-control-file" id="imageUpload" @change="handleImageChange" accept="image/*">
                                <img v-if="blog.imgPreview" :src="blog.imgPreview" alt="图片预览" style="max-width: 100%;">
                            </div>
            
                            <button class="btn " @click="addBlog()">提交</button>
                            <button type="reset" class="btn btn-secondary">清除</button>
                        </div>
                    </div>
                </div>
            </div>


            <div class="container" v-if="type==2">
                <div class="add-recipe-form">
                    
                    <div >
                        <div class="form-group">
                            <label for="recipe-name">美食名称</label>
                            <input type="text" class="form-control" id="recipe-name" name="recipe_name" v-model="food.foodName" placeholder="请输入美食名称" required>
                        </div>
                        
                        <div class="form-group">
                            <label for="recipe-details">详情</label>
                            <textarea class="form-control" id="recipe-details" name="recipe_details" v-model="food.desc" rows="5" placeholder="在此详细描述制作步骤和要点，可使用Markdown格式" required></textarea>
                        </div>
            
                        <!-- <div class="form-group">
                            <label for="recipe-image">图片上传</label>
                            <input type="file" class="form-control-file" id="recipe-image" name="recipe_image" accept="image/*" onchange="previewRecipeImage(this)">
                            <img id="recipe-preview" src="#" alt="食谱图片预览" style="max-width: 100%; display: none;">
                        </div> -->
            
                       

                        <!-- 图片上传及预览部分 -->
                        <div class="form-group">
                            <label for="imageUpload">图片上传</label>
                            <input type="file" class="form-control-file" id="recipe-image" @change="foodHandleImageChange" accept="image/*">
                            <img v-if="food.imgPreview" :src="food.imgPreview" alt="图片预览" style="max-width: 100%;">
                        </div>  

                        <div class="form-group">
                            <label for="category">分类</label>
                            <select class="form-control" id="category" name="category" v-model="food.type" required>
                                <option value="">请选择分类</option>
                                <option  v-for="item in types">{{item.type}}</option>
                                <!-- 添加更多分类选项 -->
                            </select>
                        </div>
                        
                        <div class="form-group">
                            <label for="category">食堂</label>
                            <select class="form-control" id="dininghall" name="dininghall" v-model="food.dininghall" required>
                                <option value="">请选择食堂</option>
                                <option  v-for="item in dingHalls">{{item.dininghall}}</option>
                                <!-- 添加更多分类选项 -->
                            </select>
                        </div>

                        <div class="form-group">
                            <label for="ingredients">所需材料</label>
                            <textarea class="form-control" id="ingredients" name="ingredients" v-model="food.ingredient" rows="5" placeholder="请按行分别列出所需材料，例如：
            - 鸡胸肉 200g
            - 西兰花 适量
            ..." required></textarea>
                        </div>
            
                        <div class="form-group">
                            <label for="notes">注意事项</label>
                            <textarea class="form-control" id="notes" name="notes" rows="3" v-model="food.remind" placeholder="如果有特别的烹饪技巧、过敏提示或其他重要信息，请在此填写..."></textarea>
                        </div>
            
                        <button type="submit" class="btn" @click="addFood()">提交食谱</button>
                        <button type="reset" class="btn btn-secondary">清除</button>
                    </div>
                    
                    <!-- 图片预览的JavaScript脚本 -->
                    <script>
                        function previewRecipeImage(input) {
                            var file = input.files[0];
                            if (file) {
                                var reader = new FileReader();
                                reader.onload = function(e) {
                                    document.getElementById("recipe-preview").src = e.target.result;
                                    document.getElementById("recipe-preview").style.display = "block";
                                }
                                reader.readAsDataURL(file);
                            }
                        }
                    </script>
                </div>
            </div>

        </div>
    </div>
    <!-- //contact -->
    <!--- footer --->
    <div class="footer">
        <div class="container">
            <div class="footer-grids">
                <div class="col-md-3 footer-grid">
                    <h3>关于我们</h3>
                </div>
                <div class="col-md-3 footer-grid">
                    <h3>用户协议</h3>
                </div>
                <div class="col-md-3 footer-grid">
                    <h3>隐私政策</h3>
                </div>
                <div class="col-md-3 footer-grid">
                    <h3>客户端下载</h3>
                </div>
                <div class="clearfix"> </div>
            </div>
        </div>
    </div>
    <div class="clear"> </div>
    <div class="copy-right">
        <p>Copyright &copy; 2022.美食网站版权所有</p>
    </div>
    <!--- //footer --->
    <!-- for bootstrap working -->
    <script src="js/bootstrap.js">
    </script>
    <!-- //for bootstrap working -->
   </div>
</body>
<script>
    function previewImage(input) {
        var file = input.files[0];
        if (file) {
            var reader = new FileReader();
            reader.onload = function(e) {
                document.getElementById("previewImg").src = e.target.result;
                document.getElementById("previewImg").style.display = "block";
            }
            reader.readAsDataURL(file);
        }
    }
</script>
<script>
     new Vue({
        el:"#app",
        data:{
            foodId:"",
            blogId:"",
            hello:"helloWorld",
            username:"",
            type:1,
            opt:"添加文章",
            theme:[],
            blog:{
                id:"",
                selected:"",
                title:"",
                desc:"",
                authorId:"",
                 // 添加图片预览属性
                imgPreview: "",
                tempImage: null // 存储临时图片文件
            },
            food:{
                id:"",
                // 添加图片预览属性
                imgPreview: "",
                tempImage: null, // 存储临时图片文件

                foodName:"",
                desc:"",
                type:"",
                dininghall:"",
                ingredient:"",
                remind:""
            },
            types:[],
            dingHalls:[]
           
        },
        // 创建就运行
        async created() {
            await this.isLogin()
            await this.getTheme()
            await this.getFoodTypes()
            await this.getFoodDingHall()
            await this.isUpdate()
        },
        // 方法
        methods: {
            //修改判断
            async isUpdate(){
                const searchParams = new URLSearchParams(window.location.search);  
                this.foodId = searchParams.get('foodId');
                this.blogId = searchParams.get('blogId');
                console.log(this.foodId)
                if(this.foodId!=""&&this.foodId!=null){
                    this.type=2
                    const response =  await fetch('http://127.0.0.1:5001/food/detail?id='+this.foodId)
                    const data = await response.json();
                    // 给数据赋值
                    this.food.imgPreview=data.data[0].img_url
                    this.food.tempImage=data.data[0].img_url
                    this.food.id = data.data[0].id
                    this.food.foodName=data.data[0].food_name
                    this.food.desc=data.data[0].desc
                    this.food.type=data.data[0].type
                    this.food.dininghall=data.data[0].diningHall
                    this.food.ingredient=data.data[0].ingredient
                    this.food.remind=data.data[0].remind
                    console.log("修改")
                }
                if(this.blogId!=""&&this.blog!=null){

                    this.type=1
                   
                    const response =  await fetch('http://127.0.0.1:5001/blog/getById?id='+this.blogId)
                    const data = await response.json();
                    this.blog.selected=data.data[0].theme
                    this.blog.title=data.data[0].title
                    this.blog.desc=data.data[0].desc
                    this.blog.authorId=data.data[0].authorId
                    // 添加图片预览属性
                    this.blog.imgPreview=data.data[0].img_url
                    this.blog.tempImage=data.data[0].img_url
                    this.blog.id = data.data[0].id
                }
            },
            //切换添加
            switchType(){
                if(this.type==1){
                    this.type=2
                    this.opt="添加食谱"
                }else{
                    this.type=1
                    this.opt="添加文章"
                }
            },
           // 退出登录
           logout(){
                sessionStorage.clear()
                window.location.reload()
            },
            //判断是否登录
            isLogin(){
                this.username = sessionStorage.getItem("username")
            },
            //获取博客分类
              // get请求
            async getTheme(){
                const response =  await fetch('http://127.0.0.1:5001/blog/getTheme')
                const data = await response.json();
                // 给数据赋值
                this.theme =  data.data

            },
             // 图片上传及预览
             async foodHandleImageChange(event) {
                let file = event.target.files[0];
                if (!file) return;

                // 创建一个Promise来包裹FileReader的异步操作
                let readResult = new Promise((resolve, reject) => {
                    let reader = new FileReader();
                    reader.onload = (e) => {
                        this.food.imgPreview = e.target.result; // 设置预览图像
                        // this.blog.tempImage = file; // 保存临时图片文件，供后续提交至服务器
                        resolve(e.target.result); // 读取成功后解决Promise
                    };
                    reader.onerror = reject; // 读取错误时拒绝Promise
                    reader.readAsDataURL(file); // 读取文件并转换为Base64格式
                });

                // 等待读取完成
                let base64Data = await readResult;
                
                // 提取Base64中的实际图像数据
                const imgData = base64Data.split(",")[1];

                // 准备数据
                const data = {
                    "img": imgData,
                };

                // 发送请求
                const response = await fetch("http://127.0.0.1:5001/food/putImg", {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify(data)
                });

                // 处理响应
                const res = await response.json();
                this.food.tempImage = res.data;
            },
            // 图片上传及预览
            async handleImageChange(event) {
                let file = event.target.files[0];
                if (!file) return;

                // 创建一个Promise来包裹FileReader的异步操作
                let readResult = new Promise((resolve, reject) => {
                    let reader = new FileReader();
                    reader.onload = (e) => {
                        this.blog.imgPreview = e.target.result; // 设置预览图像
                        // this.blog.tempImage = file; // 保存临时图片文件，供后续提交至服务器
                        resolve(e.target.result); // 读取成功后解决Promise
                    };
                    reader.onerror = reject; // 读取错误时拒绝Promise
                    reader.readAsDataURL(file); // 读取文件并转换为Base64格式
                });

                // 等待读取完成
                let base64Data = await readResult;
                
                // 提取Base64中的实际图像数据
                const imgData = base64Data.split(",")[1];

                // 准备数据
                const data = {
                    "img": imgData,
                };

                // 发送请求
                const response = await fetch("http://127.0.0.1:5001/blog/putImg", {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify(data)
                });

                // 处理响应
                const res = await response.json();
                this.blog.tempImage = res.data;
            },
            // 添加文章
            async addBlog(){
                if(this.blog.id!=""&&this.blog.id!=null){
                    console.log(this.blog.id);
                    var data = {
                        "title":this.blog.title,
                        "theme":this.blog.selected,
                        "desc":this.blog.desc,
                        "authorId":this.blog.authorId,
                        "imgUrl":this.blog.tempImage,
                        "id":this.blog.id
                    }
                    // 发送请求
                    const response = await fetch("http://127.0.0.1:5001/blog/update", {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json'
                        },
                        body: JSON.stringify(data)
                    });

                    // 处理响应
                    const res = await response.json();
                    if(res.code==200){
                        alert("修改成功")
                        this.blog={}
                    }
                }else{
                        // 准备数据
                    var authorId = sessionStorage.getItem("id")
                    if(authorId==null||this.blog.title==""||this.blog.desc==""||this.blog.selected==""){
                        alert("请完善信息")
                        return
                    }
                    if(this.blog.tempImage==null){
                        this.blog.tempImage ="https://nimg.ws.126.net/?url=http%3A%2F%2Fdingyue.ws.126.net%2F2024%2F0225%2F7cf1de7dj00s9eoc900gkd000r900jhp.jpg&thumbnail=660x2147483647&quality=80&type=jpg"
                    }
                    var data = {
                        "title":this.blog.title,
                        "theme":this.blog.selected,
                        "desc":this.blog.desc,
                        "authorId":authorId,
                        "imgUrl":this.blog.tempImage
                    }

                    // 发送请求
                    const response = await fetch("http://127.0.0.1:5001/blog/addBlog", {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json'
                        },
                        body: JSON.stringify(data)
                    });

                    // 处理响应
                    const res = await response.json();
                    if(res.code==200){
                        alert("添加成功")
                        this.blog={}
                    }
                }
                 
            },
            // get请求
            async getFoodTypes(){
                const response =  await fetch('http://127.0.0.1:5001/food/getType')
                const data = await response.json();
                // 给数据赋值
                this.types =  data.data

            },
              // get请求
              async getFoodDingHall(){
                const response =  await fetch('http://127.0.0.1:5001/food/getDingHall')
                const data = await response.json();
                // 给数据赋值
                this.dingHalls =  data.data

            },
            //添加美食
            async addFood(){
               if(this.food.id!=""&&this.food.id!=null){
                    var data = {
                        "id":this.food.id,
                        "food_name":this.food.foodName,
                        "desc":this.food.desc,
                        "img_url":this.food.tempImage,
                        "type":this.food.type,
                        "dingHall":this.food.dininghall,
                        "ingredient":this.food.ingredient,
                        "remind":this.food.remind
                    }
                     // 发送请求
                     const response = await fetch("http://127.0.0.1:5001/food/update", {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json'
                        },
                        body: JSON.stringify(data)
                    });

                    // 处理响应
                    const res = await response.json();
                    if(res.code==200){
                        alert("修改成功")
                        this.food={}
                    }
               }else{
                    if(this.food.desc==""||this.food.desc==""){
                        alert("请完善内容")
                        return
                    }
                    if(this.food.tempImage==null){
                        this.food.tempImage ="https://nimg.ws.126.net/?url=http%3A%2F%2Fdingyue.ws.126.net%2F2024%2F0225%2F7cf1de7dj00s9eoc900gkd000r900jhp.jpg&thumbnail=660x2147483647&quality=80&type=jpg"
                    }
                    var data = {
                        "food_name":this.food.foodName,
                        "desc":this.food.desc,
                        "img_url":this.food.tempImage,
                        "type":this.food.type,
                        "dingHall":this.food.dininghall,
                        "ingredient":this.food.ingredient,
                        "remind":this.food.remind
                    }

                    // 发送请求
                    const response = await fetch("http://127.0.0.1:5001/food/addFood", {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json'
                        },
                        body: JSON.stringify(data)
                    });

                    // 处理响应
                    const res = await response.json();
                    if(res.code==200){
                        alert("添加成功")
                        this.food={}
                    }
               }
            }
        }
    })
</script>
</html>